package com.demo.config.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.csim.express.service.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;

/**
 * 顺丰service
 *
 * @author admin
 */
@Service
public class SfSFLogisticsServiceImpl extends SFLogisticsResponse implements SFLogisticsService {

	private static final Logger log = LoggerFactory.getLogger(SfSFLogisticsServiceImpl.class);

	/**
	 * 顾客编码
	 */
	@Value("${sf.clientCode}")
	private String CLIENT_CODE;

	/**
	 * 丰桥平台生产校验码
	 */
	@Value("${sf.checkWord}")
	private String CHECK_WORD;

	/**
	 * 接口服务代码
	 */
	@Value("${sf.serviceCode}")
	private String SERVICE_CODE;

	/**
	 * 生产环境的地址
	 */
	@Value("${sf.callUrlProd}")
	private String CALL_URL_PROD;

	@Override
	public SFLogisticsSearchResponse logisticsSearch(ExpressQo request) {
		log.info("顺丰查询参数[{}]", JSON.toJSONString(request));

		if ("0".equals(request.getType())) {
			// 查询api
			return querySFApi(request);
		}
		else {
			// 查询数据库
			return null;
		}

	}

	/**
	 * 查询顺丰Api数据
	 * @param request
	 * @return
	 */
	private SFLogisticsSearchResponse querySFApi(ExpressQo request) {

		JSONArray jsonArray = new JSONArray();
		try {
			String CALL_URL_BOX = CALL_URL_PROD;

			CallExpressServiceTools client = CallExpressServiceTools.getInstance();

			HashMap<String, String> params = new HashMap<>();
			// 顾客编码 ，对应丰桥上获取的clientCode
			params.put("partnerID", CLIENT_CODE);

			params.put("requestID", UUID.randomUUID().toString().replace("-", ""));

			params.put("serviceCode", SERVICE_CODE);
			String timeStamp = String.valueOf(System.currentTimeMillis());
			params.put("timestamp", timeStamp);
			String msgData = JSON.toJSONString(request);
			params.put("msgData", msgData);
			// 数据签名
			params.put("msgDigest", CallExpressServiceTools.getMsgDigest(msgData, timeStamp, CHECK_WORD));
			String result = HttpClientUtil.post(CALL_URL_BOX, params);
			log.info("请求返回结果[{}]", result);
			JSONObject jsonObj = JSON.parseObject(result);
			if (jsonObj.containsKey("apiResultData")) {
				JSONObject json = jsonObj.getJSONObject("apiResultData");
				if (json.containsKey("msgData")) {
					json = json.getJSONObject("msgData").getJSONArray("routeResps").getJSONObject(0);
					if (json.containsKey("routes")) {
						jsonArray = json.getJSONArray("routes");
					}
				}
			}
		}
		catch (Exception e) {
			log.error("顺丰查询出错[{}]", e.getMessage());
		}
		SFLogisticsSearchResponse SFLogisticsSearchResponse = checkResult();
		return controller(SFLogisticsSearchResponse, jsonArray, request, "remark", "acceptTime");

	}

}